package com.example.zjsr.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;


@Component
public class OrdersId {

    @Autowired
    RedisUtil redisUtil;

    /**
     * 制作redis自增主键id
     * @return
     */
    public Long makeOrdersId(){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //补两位,因为一年最多三位数
        String monthFormat = String.format("%1$02d", month+1);
        //补两位，因为日最多两位数
        String dayFormat = String.format("%1$02d", day);
        //补两位，因为小时最多两位数
        String hourFormat = String.format("%1$02d", hour);
        String prefix=year+monthFormat+dayFormat+hourFormat;
        String key = "DEMO_ORDER_ID_" + prefix;
        String orderId=null;
        try {
            Long increment=redisUtil.incr(key,1);
            orderId=prefix+String.format("%1$06d",increment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Long.valueOf(orderId);
    }
}
